strtok, strtok_r(3)
synopsis
#include <string.h>
char *strtok(char *restrict str, const char *restrict delim);
char *strtok_r(char *restrict str, const char *restrict delim,
char **restrict saveptr);
strtok_r
์ thread-safeํ ๋ฒ์ ์ strtok
์ด๋ค. ์ ์ญ๋ณ์๋ฅผ ์ฌ์ฉํ์ง ์๊ณ saveptr
์ด๋ผ๋ ์ธ๋ถ๋ณ์๋ฅผ ์ฌ์ฉํ๊ธฐ ๋๋ฌธ.
example
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int
main(int argc, char *argv[])
{
char *str1, *str2, *token, *subtoken;
char *saveptr1, *saveptr2;
int j;
if (argc != 4) {
fprintf(stderr, "Usage: %s string delim subdelim\n",
argv[0]);
exit(EXIT_FAILURE);
}
for (j = 1, str1 = argv[1]; ; j++, str1 = NULL) {
token = strtok_r(str1, argv[2], &saveptr1);
if (token == NULL)
break;
printf("%d: %s\n", j, token);
for (str2 = token; ; str2 = NULL) {
subtoken = strtok_r(str2, argv[3], &saveptr2);
if (subtoken == NULL)
break;
printf("\t --> %s\n", subtoken);
}
}
exit(EXIT_SUCCESS);
}
result
$ ./a.out 'a/bbb///cc;xxx:yyy:' ':;' '/'
1: a/bbb///cc
--> a
--> bbb
--> cc
2: xxx
--> xxx
3: yyy
--> yyy
ํด์
์์ ์์ ๋ ์ด์ค for๋ฌธ์ ํ์ฉํ์ฌ nested token ๋ถ๋ฆฌ๋ฅผ ์ํํ๋ ๋ฐฉ๋ฒ์ ๋ํ๋ด๊ณ ์๋ค.
delim์ ํ์ด์ฌ ์์ delimiter์๋ ์กฐ๊ธ ๋ค๋ฅด๋ค. ๊ฐ๋ณ์ ์ธ char ๋ฐ์ดํธ ์ค ํ๋๋ผ๋ ์ผ์นํ๋ ๊ฒ์ด ์๋ค๋ฉด ํต๊ณผํ๊ธฐ ๋๋ฌธ์ด๋ค. ์๋ฅผ ๋ค์ด ์์ ์ฌ์ฉ์์ ์์ ์ฒซ๋ฒ์งธ delim์ :;
์ผ๋ก ์ฃผ์๋๋ฐ :
๋๋ ;
์ ๋ํ์ฌ ๋ชจ๋ ๋ถ๋ฆฌ๋ฅผ ์ํํ๋ค.
strtok
๋ ํ ํฐํํ ๋ฌธ์์ด์ด ๋ ์ด์ ๋จ์์์ง ์๋ ๊ฒฝ์ฐ์๋ NULL์ ๋ฆฌํดํ๊ณ ๊ทธ ์ธ์๋ ๋น์ด์์ง ์์ ๋ฌธ์์ด์ ์ฒซ๋ฒ์งธ ์ฃผ์๋ฅผ ๋ฆฌํดํ๋ค. ๋ชจ๋ delim๋ค์ Null-terminated character๋ก ์์ ๋๋ค๋ ์ ์ ์.
์ฒ์ ํธ์ถ์๋ง ์ธ์ str
์ด ํ์ํ๊ณ ๋ ๋ฒ์งธ ํธ์ถ๋ถํฐ๋ NULL
๋ก ๋ฐ๊ฟ์ ์ง์ด๋ฃ๋ ์ฝ๋๋ฅผ ํ์ธํ ์ ์๋ค.